<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .penBtn {
        margin: 10px;
      }
      #svg {
        width: 100%;
        height: 600px;
        color: #a2a2a2;
        box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        margin: 10px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <button class="penBtn">随手画</button>
    <svg id="svg"></svg>

    <script>
      const svg = document.querySelector('#svg');
      const penBtn = document.querySelector('.penBtn');

      let isPen = false;
      penBtn.onclick = (e) => {
        if (!isPen) {
          isPen = true;
          penBtn.style.backgroundColor = 'rgb(248, 170, 74)';
        } else {
          isPen = false;
          penBtn.style.backgroundColor = 'rgb(229, 229, 229)';
        }
      };

      let isDraw = false;
      let path;

      svg.onpointerdown = (e) => {
        console.log(e);
        if (isPen) {
          isDraw = true;
          let p = point(e, svg);
          path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
          path.setAttribute(
            'style',
            'fill:transparent;stroke-width:1;stroke:black'
          );
          path.setAttribute('d', 'M ' + p.x + ' ' + p.y);
          svg.appendChild(path);
        }
      };
      svg.onpointerup = (e) => {
        if (isPen) {
          isDraw = false;
          svg.appendChild(path);
        }
      };
      svg.onpointermove = (e) => {
        if (isPen) {
          let p = point(e, svg);
          if (isDraw) {
            path.setAttribute(
              'd',
              path.getAttribute('d') + 'L ' + p.x + ' ' + p.y
            );
            svg.appendChild(path);
          }
        }
      };
      function point(e, element) {
        let x =
          e.offsetX -
          parseInt(window.getComputedStyle(element, null).paddingLeft);
        let y =
          e.offsetY -
          parseInt(window.getComputedStyle(element, null).paddingTop);
        return {
          x,
          y,
        };
      }
    </script>
  </body>
</html>
